<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>FITS Viewer</title>
    <script src="http://10.34.1.111:5066/firefly/firefly_loader.js"></script>
    <style>
        body {
            font-family: sans-serif;
            margin: 0;
            padding: 0;
        }

        .fits-container {
            display: flex;
            flex-wrap: wrap;
            width: 99vw;
            height: calc(100vh - 60px);
        }

        .fits-panel {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>

    <h2 style="padding: 5px; margin: 0;" id="title">FITS Viewer</h2>
    <div class="fits-container" id="fitsContainer"></div>

    <script>
        let hasFireflyLoaded = false;

        function getQueryParam(name) {
            const params = new URLSearchParams(window.location.search);
            return params.get(name);
        }

        async function getDatasetInfo(datasetName) {
            const datasetResp = await fetch('data/datasets.json');
            const datasetList = await datasetResp.json();
            const dataset = datasetList.find(d => d.name === datasetName);
            if (!dataset) throw new Error(`Dataset "${datasetName}" not found.`);
            return dataset;
        }

        async function getPreviewData(dataset) {
            const previewResp = await fetch(dataset.dataInfo);
            return await previewResp.json();
        }

        async function onFireflyLoaded() {
            if (hasFireflyLoaded) return;
            hasFireflyLoaded = true;

            const targetName = getQueryParam('name');
            const datasetName = getQueryParam('datasetname');

            if (!targetName || !datasetName) {
                document.getElementById('title').innerText = `Missing "name" or "datasetname" in URL`;
                return;
            }

            let dataset, data;
            try {
                dataset = await getDatasetInfo(datasetName);
                data = await getPreviewData(dataset);
            } catch (err) {
                document.getElementById('title').innerText = `Error loading dataset: ${err.message}`;
                return;
            }

            const entry = data.find(item => item.orig_name === targetName);
            if (!entry) {
                document.getElementById('title').innerText = `Target "${targetName}" not found in dataset "${datasetName}".`;
                return;
            }

            document.getElementById('title').innerText = `FITS Viewer - ${targetName} [${datasetName}]`;

            // 读取并排序 fitsShowColumn，构造 imageMeta 列表
            const fitsShowColumn = (dataset.fitsShowColumn || []).sort((a, b) => a.colIdx - b.colIdx);
            const defaultRegFileKey = dataset.defaultRegFileKey;
            const imageMeta = fitsShowColumn.map(item => ({
                key: item.keyName,
                title: item.showColumnName
            }));

            setTimeout(() => {
                firefly.setGlobalImageDef({
                    ZoomType: 'TO_WIDTH',
                    ColorTable: 0
                });

                show1Window(entry, imageMeta);
            }, 500);

            setTimeout(() => {
                firefly.action.dispatchWcsMatch({
                    matchType: 'Pixel',
                    lockMatch: true
                });

                const crsegRegFile = entry[defaultRegFileKey];
                console.log(entry)
                console.log(defaultRegFileKey)
                console.log(crsegRegFile)
                if (crsegRegFile) {
                    firefly.action.dispatchCreateRegionLayer(
                        'region112',
                        'Region Layer 1',
                        crsegRegFile,
                        null,
                        imageMeta.map(m => m.key)
                    );
                }
            }, 1500);
        }

        window.addEventListener('load', () => {
            if (window.firefly) {
                onFireflyLoaded();
            } else {
                window.fireflyLoaded = onFireflyLoaded;
            }
        });

        function show1Window(fitsFiles, imageMeta) {
            const divId = 'image_div_4';
            const div = document.createElement('div');
            div.className = 'fits-panel';
            div.id = divId;
            const container = document.getElementById('fitsContainer');
            container.appendChild(div);

            imageMeta.forEach(({ key, title }) => {
                const filePath = fitsFiles[key];
                if (!filePath) return;
                firefly.showImage(divId, {
                    file: filePath,
                    plotId: key,
                    Title: title || key
                });
            });
        }

        function show4Window(fitsFiles, imageKeys) {
            const container = document.getElementById('fitsContainer');
            imageKeys.forEach((key, idx) => {
                const filePath = fitsFiles[key];
                if (!filePath) return;

                const divId = 'image_div_' + idx;
                const div = document.createElement('div');
                div.className = 'fits-panel';
                div.id = divId;
                container.appendChild(div);

                firefly.showImage(divId, {
                    file: filePath,
                    plotId: key,
                    Title: key
                });
            });
        }
    </script>

</body>

</html>
